package com.example.backend.controller.admin;

import com.example.backend.common.annotation.OperationLog;
import com.example.backend.common.api.R;
import com.example.backend.common.api.ResultCode;
import com.example.backend.common.exception.BusinessException;
import com.example.backend.common.tree.MenuTree;
import com.example.backend.common.utils.SecurityUtils;
import com.example.backend.dto.PermissionDTO;
import com.example.backend.entity.Permission;
import com.example.backend.entity.User;
import com.example.backend.service.PermissionService;
import com.example.backend.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 权限管理控制器
 */
@RestController
@RequestMapping("/admin/permission")
@RequiredArgsConstructor
public class PermissionController {
    
    private final PermissionService permissionService;
    private final UserService userService;
    
    /**
     * 获取权限树
     */
    @GetMapping("/tree")
    @PreAuthorize("hasAuthority('system:menu:list')")
    public R<List<Permission>> getPermissionTree() {
        return R.ok(permissionService.buildPermissionTree());
    }
    
    /**
     * 获取所有权限列表
     */
    @GetMapping("/list")
    @PreAuthorize("hasAuthority('system:menu:list')")
    public R<List<Permission>> list() {
        return R.ok(permissionService.list());
    }
    
    /**
     * 创建权限
     */
    @OperationLog(module = "权限管理", type = "新增", description = "新增权限")
    @PostMapping
    @PreAuthorize("hasAuthority('system:menu:add')")
    public R<Void> createPermission(@Validated(PermissionDTO.Create.class) @RequestBody PermissionDTO permissionDTO) {
        permissionService.createPermission(permissionDTO);
        return R.ok();
    }
    
    /**
     * 更新权限
     */
    @OperationLog(module = "权限管理", type = "修改", description = "修改权限")
    @PutMapping
    @PreAuthorize("hasAuthority('system:menu:edit')")
    public R<Void> updatePermission(@Validated(PermissionDTO.Update.class) @RequestBody PermissionDTO permissionDTO) {
        permissionService.updatePermission(permissionDTO);
        return R.ok();
    }
    
    /**
     * 删除权限
     */
    @OperationLog(module = "权限管理", type = "删除", description = "删除权限")
    @DeleteMapping("/{id}")
    @PreAuthorize("hasAuthority('system:menu:delete')")
    public R<Void> deletePermission(@PathVariable Long id) {
        permissionService.deletePermission(id);
        return R.ok();
    }

    /**
     * 获取用户菜单树
     */
    @GetMapping("/user/menu")
    public R<List<MenuTree>> getUserMenuTree() {
        Long currentUserId = SecurityUtils.getCurrentUserId();
        return R.ok(permissionService.getUserMenuTree(currentUserId));
    }
}